<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Topic extends Model
{
    public $timestamps = false;
    protected $primaryKey = 'tid';

    /**
     * 获取投票主题数组，给主界面显示用的
     * @return array 投票主题数组
     */
    public function getTopics() {
        return $this->orderBy('pub_time', 'desc')->paginate(5);
    }

    public function searchTopics($search) {
        return $this->where('title','like',"%$search%")->orderBy('pub_time', 'desc')->paginate(5);
    } 

    /**
     * 获取单个投票主题，给投票界面使用
     * @param $tid 投票主题id
     * @return array 投票主题信息，包括选项信息
     */
    public function getTopic($tid) {
        $topic = $this->find($tid);         // 查询topic信息
        $info = $topic->toArray();          // 把查询结果放到数组中
        $sel = $topic->selects->toArray();  // 查询选项信息，并放到数组中
        $rs = [];
        $rs = array_merge($rs, $info);
        $rs['selects'] = $sel;
        return $rs;
    }

    /**
     * 保存投票主题
     *
     *
        $info = [
            'uid'=>'用户id',
            'title'=>'主题',
            'desc'=>'内容',
            'type'=>1,
            'is_pic'=>0,
            'selects'=>[
                ['link'=>'选项1','pic'=>'url'],
                ['link'=>'选项1','pic'=>'url'],
                ['link'=>'选项1','pic'=>'url']
            ]
        ];

     * @param $info
     */
    public function saveTopic($info) {
        $top_id = DB::table('topics')->insertGetId([
            'uid' => $info['uid'],
            'title' => $info['title'],
            'desc' => $info['desc'],
            'type' => $info['type'],
            'is_pic' => $info['is_pic'],
            'pub_time' => time(),
        ]);

        $sel_array = [];
        $sel_items = $info['selects'];
        for ($i = 0; $i < count($sel_items); $i++) {
            $sel = [];
            $sel['tid'] = $top_id;
            $sel['sid'] = $i + 1;
            $sel['link'] = $sel_items[$i]['link'];
            $sel['pic'] = $sel_items[$i]['pic'];
            $sel_array[] = $sel;
        }
        DB::table('selects')->insert($sel_array);
    }

    public function selects()
    {
        return $this->hasMany('App\Select', 'tid', 'tid');
    }
}
